from flask import g
from sqlalchemy.orm import Query
from sqlalchemy import event
from sqlalchemy.dialects import postgresql  # 也可换成 mysql/sqlite 看你用的数据库


# 租户查询类，通过重写查询方法实现自动过滤
class TenantQuery(Query):
    def all(self):
        """重写all方法，自动添加租户过滤"""
        from flask import current_app
        if current_app and current_app.debug:
            current_app.logger.debug("🔍 TenantQuery.all() 被调用")

        # 如果查询有LIMIT/OFFSET，需要特殊处理
        if self._has_limit_or_offset():
            if current_app and current_app.debug:
                current_app.logger.debug("🔍 查询有LIMIT/OFFSET，使用特殊处理")
            return self._handle_limit_query()
        else:
            filtered_query = self._get_tenant_filtered_query()
            if current_app and current_app.debug:
                # current_app.logger.debug(f"🔍 过滤后的查询: {filtered_query}")
                pass
            return Query.all(filtered_query)

    def first(self):
        """重写first方法，自动添加租户过滤"""
        filtered_query = self._get_tenant_filtered_query()
        return Query.first(filtered_query)

    def one(self):
        """重写one方法，自动添加租户过滤"""
        filtered_query = self._get_tenant_filtered_query()
        return Query.one(filtered_query)

    def one_or_none(self):
        """重写one_or_none方法，自动添加租户过滤"""
        filtered_query = self._get_tenant_filtered_query()
        return Query.one_or_none(filtered_query)

    def scalar(self):
        """重写scalar方法，自动添加租户过滤"""
        filtered_query = self._get_tenant_filtered_query()
        return Query.scalar(filtered_query)

    def count(self):
        """重写count方法，自动添加租户过滤"""
        from flask import current_app
        if current_app and current_app.debug:
            current_app.logger.debug("🔍 TenantQuery.count() 被调用")

        # 如果查询有LIMIT/OFFSET，需要特殊处理
        if self._has_limit_or_offset():
            if current_app and current_app.debug:
                current_app.logger.debug("🔍 count查询有LIMIT/OFFSET，使用特殊处理")
            return self._handle_limit_count()
        else:
            filtered_query = self._get_tenant_filtered_query()
            if current_app and current_app.debug:
                current_app.logger.debug(f"🔍 count过滤后的查询: {filtered_query}")
            return Query.count(filtered_query)

    def delete(self):
        """重写delete方法，自动添加租户过滤"""
        filtered_query = self._get_tenant_filtered_query()
        return Query.delete(filtered_query)

    def update(self, values, synchronize_session='evaluate'):
        """重写update方法，自动添加租户过滤"""
        filtered_query = self._get_tenant_filtered_query()
        return Query.update(filtered_query, values, synchronize_session)

    def get(self, ident):
        """重写get方法，自动添加租户过滤"""
        model = self._get_query_model()
        if model and self._should_filter_tenant(model):
            tenant_id = self._get_current_tenant_id()
            if tenant_id is not None:
                # 获取主键字段名
                pk_name = model.__mapper__.primary_key[0].name
                return Query.filter(self, model.tenant_id == tenant_id,
                                    getattr(model, pk_name) == ident).first()
        return Query.get(self, ident)

    def get_or_404(self, ident, description=None):
        """获取对象，如果不存在则返回404错误"""
        from flask import abort
        obj = self.get(ident)
        if obj is None:
            abort(404, description=description)
        return obj

    def _get_tenant_filtered_query(self):
        """获取添加了租户过滤的查询对象"""
        from flask import current_app

        # 获取查询的模型类
        model = self._get_query_model()
        if current_app and current_app.debug:
            current_app.logger.debug(f"🔍 查询的模型类: {model}")

        if not model or not self._should_filter_tenant(model):
            if current_app and current_app.debug:
                current_app.logger.debug(f"🔍 不需要过滤租户，模型: {model}")
            return self

        # 获取当前租户ID
        tenant_id = self._get_current_tenant_id()
        if current_app and current_app.debug:
            current_app.logger.debug(f"🔍 当前租户ID: {tenant_id}")

        # 检查是否已经有租户过滤条件
        if self._has_tenant_filter():
            if current_app and current_app.debug:
                current_app.logger.debug("🔍 已有租户过滤条件，跳过")
            return self

        # 检查查询是否已经有LIMIT或OFFSET
        if self._has_limit_or_offset():
            if current_app and current_app.debug:
                current_app.logger.debug("🔍 查询已有LIMIT/OFFSET，无法添加过滤条件")
            return self

        if tenant_id is None:
            if current_app and current_app.debug:
                current_app.logger.debug("🔍 租户ID为空，返回空查询（强制租户隔离）")
            # 强制租户隔离：没有租户ID时返回空查询
            try:
                return Query.filter(self, model.tenant_id == -999999)  # 使用不存在的租户ID
            except Exception as e:
                if current_app and current_app.debug:
                    current_app.logger.debug(f"🔍 添加空查询过滤失败: {str(e)}")
                return self

        # 添加租户过滤条件
        try:
            filtered_query = Query.filter(self, model.tenant_id == tenant_id)
            if current_app and current_app.debug:
                current_app.logger.debug(f"🔍 添加租户过滤后的查询: {filtered_query}")
            return filtered_query
        except Exception as e:
            if current_app and current_app.debug:
                current_app.logger.debug(f"🔍 添加租户过滤失败: {str(e)}")
            return self

    def _get_query_model(self):
        """获取查询的模型类"""
        try:
            if hasattr(self, 'column_descriptions'):
                descriptions = self.column_descriptions
                if descriptions and len(descriptions) > 0:
                    return descriptions[0]['type']
        except Exception:
            pass
        return None

    def _should_filter_tenant(self, model):
        """判断是否需要租户过滤"""
        from flask import has_request_context, current_app

        # 没有请求上下文时不过滤
        if not has_request_context():
            if current_app and current_app.debug:
                current_app.logger.debug("🔍 没有请求上下文，不过滤")
            return False

        # 检查模型是否有tenant_id字段
        if not hasattr(model, 'tenant_id'):
            if current_app and current_app.debug:
                current_app.logger.debug(f"🔍 模型 {model} 没有tenant_id字段，不过滤")
            return False

        # 跳过租户表本身
        if getattr(model, '__name__', '') == 'Tenant':
            if current_app and current_app.debug:
                current_app.logger.debug("🔍 跳过租户表本身")
            return False

        # 超级管理员不过滤
        if getattr(g, 'is_super_admin', False):
            if current_app and current_app.debug:
                current_app.logger.debug("🔍 超级管理员，不过滤")
            return False

        # 跳过租户检查的情况
        if getattr(g, 'skip_tenant_check', False):
            if current_app and current_app.debug:
                current_app.logger.debug("🔍 跳过租户检查，不过滤")
            return False

        if current_app and current_app.debug:
            current_app.logger.debug(f"🔍 需要过滤租户，模型: {model}")

        return True

    def _get_current_tenant_id(self):
        """获取当前租户ID"""
        from flask import has_request_context, current_app

        if not has_request_context():
            if current_app and current_app.debug:
                current_app.logger.debug("🔍 没有请求上下文，租户ID为None")
            return None

        tenant_id = getattr(g, 'tenant_id', None)
        if current_app and current_app.debug:
            current_app.logger.debug(f"🔍 从g获取的租户ID: {tenant_id}")
        return tenant_id

    def _has_tenant_filter(self):
        """检查是否已经有租户过滤条件"""
        try:
            if hasattr(self, 'whereclause') and self.whereclause is not None:
                # 简单检查SQL中是否包含tenant_id
                sql_str = str(self.whereclause).lower()
                return 'tenant_id' in sql_str
        except Exception:
            pass
        return False

    def _has_limit_or_offset(self):
        """检查查询是否已经有LIMIT或OFFSET"""
        from flask import current_app
        try:
            # 检查是否有limit
            if hasattr(self, '_limit') and self._limit is not None:
                if current_app and current_app.debug:
                    current_app.logger.debug(f"🔍 查询有_limit: {self._limit}")
                return True
            # 检查是否有offset
            if hasattr(self, '_offset') and self._offset is not None:
                if current_app and current_app.debug:
                    current_app.logger.debug(f"🔍 查询有_offset: {self._offset}")
                return True

            # 检查SQL字符串中是否包含LIMIT
            sql_str = str(self).lower()
            if 'limit' in sql_str:
                if current_app and current_app.debug:
                    current_app.logger.debug(f"🔍 SQL中包含LIMIT: {sql_str}")
                return True

        except Exception as e:
            if current_app and current_app.debug:
                current_app.logger.debug(f"🔍 检查LIMIT/OFFSET时出错: {str(e)}")
        return False

    def _force_add_tenant_filter(self):
        """强制添加租户过滤条件，即使有LIMIT/OFFSET"""
        from flask import current_app

        # 获取查询的模型类
        model = self._get_query_model()
        if not model or not self._should_filter_tenant(model):
            return self

        # 获取当前租户ID
        tenant_id = self._get_current_tenant_id()
        if tenant_id is None:
            # 强制租户隔离：没有租户ID时返回空查询
            try:
                # 直接修改whereclause属性
                from sqlalchemy import and_
                empty_condition = model.tenant_id == -999999
                if self.whereclause is not None:
                    self.whereclause = and_(self.whereclause, empty_condition)
                else:
                    self.whereclause = empty_condition
                return self
            except Exception as e:
                if current_app and current_app.debug:
                    current_app.logger.debug(f"🔍 强制添加空查询过滤失败: {str(e)}")
                return self

        # 检查是否已经有租户过滤条件
        if self._has_tenant_filter():
            return self

        # 强制添加租户过滤条件 - 直接修改whereclause
        try:
            from sqlalchemy import and_
            tenant_condition = model.tenant_id == tenant_id

            # 直接修改查询的whereclause属性
            if hasattr(self, 'whereclause'):
                if self.whereclause is not None:
                    self.whereclause = and_(self.whereclause, tenant_condition)
                else:
                    self.whereclause = tenant_condition
            else:
                # 如果没有whereclause属性，尝试设置
                self.whereclause = tenant_condition

            if current_app and current_app.debug:
                current_app.logger.debug(f"🔍 强制添加租户过滤成功: tenant_id={tenant_id}")
            return self
        except Exception as e:
            if current_app and current_app.debug:
                current_app.logger.debug(f"🔍 强制添加租户过滤失败: {str(e)}")
            return self

    def paginate(self, page=None, per_page=None, error_out=True, max_per_page=None):
        """重写paginate方法，确保分页功能正常"""
        from flask import current_app

        # 设置默认值
        if page is None:
            page = 1
        if per_page is None:
            per_page = current_app.config.get('POSTS_PER_PAGE', 20)
        if max_per_page is not None:
            per_page = min(per_page, max_per_page)

        # 验证参数
        if page < 1:
            if error_out:
                raise ValueError('Page must be >= 1')
            page = 1

        # 计算偏移量
        offset = (page - 1) * per_page

        # 获取总数
        total = self.count()

        # 计算总页数
        pages = (total - 1) // per_page + 1 if total > 0 else 1

        # 检查页码是否超出范围
        if page > pages and total > 0:
            if error_out:
                raise ValueError(f'Page {page} out of range (1-{pages})')
            page = pages
            offset = (page - 1) * per_page

        # 获取当前页的数据
        items = self.offset(offset).limit(per_page).all()

        # 创建简单的分页对象
        class SimplePagination:
            def __init__(self, items, page, per_page, total, pages):
                self.items = items
                self.page = page
                self.per_page = per_page
                self.total = total
                self.pages = pages
                self.has_prev = page > 1
                self.has_next = page < pages
                self.prev_num = page - 1 if self.has_prev else None
                self.next_num = page + 1 if self.has_next else None

        return SimplePagination(items, page, per_page, total, pages)


def auto_set_tenant_id(mapper, connection, target):
    """自动为模型实例设置租户ID"""
    from flask import current_app, has_request_context

    try:
        # 跳过租户表本身
        if target.__class__.__name__ == 'Tenant':
            return

        # 检查模型是否有tenant_id字段
        if not hasattr(target, 'tenant_id'):
            return

        # 如果已经设置了tenant_id，则不覆盖
        current_tenant_id = getattr(target, 'tenant_id', None)
        if current_tenant_id is not None:
            if current_app.debug:
                current_app.logger.debug(f"✅ {target.__class__.__name__} 已有租户ID: {current_tenant_id}")
            return

        # 跳过超级管理员和特殊情况
        if (getattr(g, 'is_super_admin', False) or
                getattr(g, 'skip_tenant_check', False) or
                getattr(g, 'skip_tenant_auto_set', False)):
            # 超级管理员或跳过检查时，仍需要设置默认租户ID以避免数据库约束错误
            target.tenant_id = getattr(g, 'tenant_id', 1)
            if current_app.debug:
                current_app.logger.debug(f"跳过自动设置租户ID检查，使用租户ID: {target.tenant_id}")
            return

        # 从全局变量获取租户ID
        tenant_id = getattr(g, 'tenant_id', None)

        if tenant_id is not None:
            target.tenant_id = tenant_id
            if current_app.debug:
                current_app.logger.debug(f"✅ 已为 {target.__class__.__name__} 设置租户ID: {tenant_id}")
        else:
            # 如果没有租户ID，设置默认值1
            target.tenant_id = 1
            current_app.logger.warning(f"⚠️ 无法获取租户ID，为 {target.__class__.__name__} 设置默认租户ID: 1")

    except Exception as e:
        current_app.logger.error(f"❌ 自动设置租户ID时发生错误: {str(e)}")
        # 发生错误时也设置默认值，避免数据库约束错误
        if hasattr(target, 'tenant_id') and getattr(target, 'tenant_id', None) is None:
            target.tenant_id = 1
            current_app.logger.info(f"✅ 错误处理中为 {target.__class__.__name__} 设置默认租户ID: 1")


def register_tenant_events(db):
    """注册租户相关的数据库事件"""
    from flask import current_app

    # 动态获取所有模型类
    registered_count = 0
    skipped_models = []
    registered_models = []

    # 遍历所有已注册的模型
    for model_class in db.Model.registry._class_registry.values():
        # 跳过非模型类（如字符串引用等）
        if not hasattr(model_class, '__tablename__'):
            continue

        # 跳过租户表本身
        if getattr(model_class, '__name__', '') == 'Tenant':
            continue

        # 检查模型是否有tenant_id字段
        if hasattr(model_class, 'tenant_id'):
            try:
                # 检查是否已经注册过事件（避免重复注册）
                existing_listeners = event.contains(model_class, 'before_insert', auto_set_tenant_id)
                if not existing_listeners:
                    event.listen(model_class, 'before_insert', auto_set_tenant_id)
                    registered_models.append(model_class.__name__)
                    registered_count += 1
                    if current_app.debug:
                        current_app.logger.debug(f"✅ 已为 {model_class.__name__} 注册租户ID自动设置事件")
                else:
                    if current_app.debug:
                        current_app.logger.debug(f"⚠️ {model_class.__name__} 已注册过租户ID事件，跳过")
            except Exception as e:
                current_app.logger.error(f"❌ 为 {model_class.__name__} 注册事件时出错: {str(e)}")
                skipped_models.append(model_class.__name__)
        else:
            skipped_models.append(model_class.__name__)
            if current_app.debug:
                current_app.logger.debug(f"⚠️ {model_class.__name__} 没有tenant_id字段，跳过事件注册")

    # 记录注册结果
    current_app.logger.info(f"🎉 共为 {registered_count} 个模型注册了租户ID自动设置事件")
    if current_app.debug and registered_models:
        current_app.logger.debug(f"已注册模型: {', '.join(registered_models)}")
    if current_app.debug and skipped_models:
        current_app.logger.debug(f"跳过的模型: {', '.join(skipped_models)}")

    return registered_count


def setup_query_filtering():
    """
    设置查询过滤事件监听
    """
    from app.core.extensions import db
    from flask import current_app
    from sqlalchemy import event

    # 监听查询执行前的事件
    @event.listens_for(db.engine, 'before_cursor_execute')
    def before_cursor_execute(conn, cursor, statement, parameters, context, executemany):
        """在SQL执行前自动添加租户过滤条件"""
        try:
            # 只处理SELECT语句
            if not statement.strip().upper().startswith('SELECT'):
                return

            # 检查是否需要添加租户过滤
            if _should_add_tenant_filter(statement):
                # 修改SQL语句添加租户过滤条件
                modified_statement, modified_params = _add_tenant_filter_to_sql(statement, parameters)
                if modified_statement != statement:
                    # 替换原始语句
                    context.statement = modified_statement
                    if isinstance(parameters, dict):
                        parameters.update(modified_params)
                    elif isinstance(parameters, (list, tuple)) and modified_params:
                        parameters = list(parameters) + list(modified_params.values())

        except Exception as e:
            if current_app and current_app.debug:
                current_app.logger.debug(f"添加租户过滤时出错: {str(e)}")

    current_app.logger.info("🎉 已设置SQL级别的租户过滤")


def _should_add_tenant_filter(statement):
    """判断是否需要添加租户过滤"""
    from flask import has_request_context

    # 没有请求上下文时不过滤
    if not has_request_context():
        return False

    # 超级管理员不过滤
    if getattr(g, 'is_super_admin', False):
        return False

    # 跳过租户检查的情况
    if getattr(g, 'skip_tenant_check', False):
        return False

    # 获取当前租户ID
    tenant_id = getattr(g, 'tenant_id', None)
    if tenant_id is None:
        return False

    # 检查SQL是否涉及有tenant_id字段的表
    statement_lower = statement.lower()

    # 需要过滤的表名列表
    tenant_tables = [
        'users', 'articles', 'banners', 'notices', 'admins', 'agents',
        'orders', 'recognition_records', 'commission_logs', 'system_logs',
        'admin_logs', 'feedbacks', 'permissions', 'roles', 'menus',
        'activation_codes', 'activation_code_batches', 'payment_logs',
        'plans', 'usage_records', 'commissions', 'withdraw_logs'
    ]

    # 检查是否查询了需要过滤的表
    for table in tenant_tables:
        if f'from {table}' in statement_lower or f'join {table}' in statement_lower:
            # 检查是否已经有tenant_id过滤条件
            if 'tenant_id' not in statement_lower:
                return True

    return False


def _add_tenant_filter_to_sql(statement, parameters):
    """为SQL语句添加租户过滤条件"""
    try:
        tenant_id = getattr(g, 'tenant_id', None)
        if tenant_id is None:
            return statement, parameters

        statement_lower = statement.lower()

        # 需要过滤的表名列表
        tenant_tables = [
            'users', 'articles', 'banners', 'notices', 'admins', 'agents',
            'orders', 'recognition_records', 'commission_logs', 'system_logs',
            'admin_logs', 'feedbacks', 'permissions', 'roles', 'menus',
            'activation_codes', 'activation_code_batches', 'payment_logs',
            'plans', 'usage_records', 'commissions', 'withdraw_logs'
        ]

        modified_statement = statement
        modified_params = {}

        for table in tenant_tables:
            # 查找表名在SQL中的位置
            from_pattern = f'from {table}'
            join_pattern = f'join {table}'

            if from_pattern in statement_lower:
                # 添加WHERE条件
                if 'where' in statement_lower:
                    # 已有WHERE子句，添加AND条件
                    where_pos = statement_lower.find('where')
                    before_where = statement[:where_pos + 5]  # 包含WHERE
                    after_where = statement[where_pos + 5:]
                    modified_statement = f"{before_where} {table}.tenant_id = %(tenant_id)s AND{after_where}"
                else:
                    # 没有WHERE子句，添加WHERE条件
                    # 查找ORDER BY, GROUP BY, LIMIT等子句的位置
                    order_pos = statement_lower.find('order by')
                    group_pos = statement_lower.find('group by')
                    limit_pos = statement_lower.find('limit')

                    insert_pos = len(statement)
                    for pos in [order_pos, group_pos, limit_pos]:
                        if pos != -1 and pos < insert_pos:
                            insert_pos = pos

                    if insert_pos < len(statement):
                        before_clause = statement[:insert_pos].strip()
                        after_clause = statement[insert_pos:]
                        modified_statement = f"{before_clause} WHERE {table}.tenant_id = %(tenant_id)s {after_clause}"
                    else:
                        modified_statement = f"{statement} WHERE {table}.tenant_id = %(tenant_id)s"

                modified_params['tenant_id'] = tenant_id
                break  # 只处理第一个匹配的表

        return modified_statement, modified_params

    except Exception as e:
        from flask import current_app
        if current_app and current_app.debug:
            current_app.logger.debug(f"修改SQL时出错: {str(e)}")
        return statement, parameters


def setup_tenant_filtering():
    """
    为所有模型设置租户过滤功能
    """
    from app.core.extensions import db
    from flask import current_app

    filtered_count = 0

    # 遍历所有模型
    for model_class in db.Model.registry._class_registry.values():
        if not hasattr(model_class, '__tablename__'):
            continue

        # 跳过租户表本身
        if getattr(model_class, '__name__', '') == 'Tenant':
            continue

        # 检查是否有tenant_id字段
        if hasattr(model_class, 'tenant_id'):
            # 添加租户过滤方法
            _add_tenant_methods(model_class)
            # 设置模型使用TenantQuery类
            model_class.query_class = TenantQuery
            filtered_count += 1

            if current_app.debug:
                current_app.logger.debug(f"✅ 已为 {model_class.__name__} 添加租户过滤方法")

    current_app.logger.info(f"🎉 共为 {filtered_count} 个模型添加了租户过滤方法")
    return filtered_count


def _replace_query_property(model_class):
    """
    替换模型的query属性为自动过滤版本（暂时禁用，避免复杂性）
    """
    # 暂时不替换query属性，避免复杂的技术问题
    pass


def _add_tenant_methods(model_class):
    """
    为模型类添加租户相关的查询方法
    """

    @classmethod
    def tenant_query(cls):
        """
        获取当前租户的查询对象
        """
        from flask import has_request_context

        query = cls.query

        # 检查是否需要过滤
        if not has_request_context():
            return query

        # 超级管理员不过滤
        if getattr(g, 'is_super_admin', False):
            return query

        # 跳过租户检查的情况
        if getattr(g, 'skip_tenant_check', False):
            return query

        # 添加租户过滤条件
        tenant_id = getattr(g, 'tenant_id', None)
        if tenant_id is not None:
            query = query.filter(cls.tenant_id == tenant_id)

        return query

    @classmethod
    def all_tenants_query(cls):
        """
        获取所有租户的查询对象（跳过租户过滤）
        """
        return cls.query

    @classmethod
    def tenant_get(cls, id):
        """
        根据ID获取当前租户的记录
        """
        return cls.tenant_query().filter(cls.id == id).first()

    @classmethod
    def tenant_all(cls):
        """
        获取当前租户的所有记录
        """
        return cls.tenant_query().all()

    @classmethod
    def tenant_count(cls):
        """
        统计当前租户的记录数量
        """
        return cls.tenant_query().count()

    @classmethod
    def tenant_filter_by(cls, **kwargs):
        """
        按条件过滤当前租户的记录
        """
        return cls.tenant_query().filter_by(**kwargs)

    @classmethod
    def tenant_paginate(cls, page=1, per_page=20, error_out=True, max_per_page=None):
        """
        分页获取当前租户的记录
        """
        return cls.tenant_query().paginate(
            page=page,
            per_page=per_page,
            error_out=error_out,
            max_per_page=max_per_page
        )

    # 将方法绑定到模型类
    model_class.tenant_query = tenant_query
    model_class.all_tenants_query = all_tenants_query
    model_class.tenant_get = tenant_get
    model_class.tenant_all = tenant_all
    model_class.tenant_count = tenant_count
    model_class.tenant_filter_by = tenant_filter_by
    model_class.tenant_paginate = tenant_paginate


def skip_tenant_filter():
    """
    跳过租户过滤的上下文管理器

    使用示例:
    with skip_tenant_filter():
        # 在这里的查询不会自动过滤租户ID
        all_users = User.query.all()  # 获取所有租户的用户
    """
    from contextlib import contextmanager

    @contextmanager
    def _skip_tenant_filter():
        original_skip = getattr(g, 'skip_tenant_check', False)
        g.skip_tenant_check = True
        try:
            yield
        finally:
            g.skip_tenant_check = original_skip

    return _skip_tenant_filter()


# 为TenantQuery类添加处理LIMIT查询的方法
def _handle_limit_query(self):
    """处理有LIMIT/OFFSET的查询"""
    from flask import current_app

    # 获取查询的模型类
    model = self._get_query_model()
    if not model or not self._should_filter_tenant(model):
        return Query.all(self)

    # 获取当前租户ID
    tenant_id = self._get_current_tenant_id()

    if tenant_id is None:
        # 强制租户隔离：没有租户ID时返回空结果
        if current_app and current_app.debug:
            current_app.logger.debug("🔍 LIMIT查询没有租户ID，返回空结果")
        return []

    # 检查是否已经有租户过滤条件
    if self._has_tenant_filter():
        if current_app and current_app.debug:
            current_app.logger.debug("🔍 LIMIT查询已有租户过滤，直接执行")
        return Query.all(self)

    # 执行查询并手动过滤结果
    if current_app and current_app.debug:
        current_app.logger.debug("🔍 LIMIT查询执行后手动过滤")

    try:
        # 执行原始查询
        results = Query.all(self)

        # 手动过滤结果
        filtered_results = [r for r in results if hasattr(r, 'tenant_id') and r.tenant_id == tenant_id]

        if current_app and current_app.debug:
            current_app.logger.debug(f"🔍 LIMIT查询原始结果: {len(results)}, 过滤后: {len(filtered_results)}")

        return filtered_results

    except Exception as e:
        if current_app and current_app.debug:
            current_app.logger.debug(f"🔍 LIMIT查询处理失败: {str(e)}")
        return []


# 为TenantQuery类添加处理LIMIT count查询的方法
def _handle_limit_count(self):
    """处理有LIMIT/OFFSET的count查询"""
    from flask import current_app

    # 获取查询的模型类
    model = self._get_query_model()
    if not model or not self._should_filter_tenant(model):
        return Query.count(self)

    # 获取当前租户ID
    tenant_id = self._get_current_tenant_id()

    if tenant_id is None:
        # 强制租户隔离：没有租户ID时返回0
        if current_app and current_app.debug:
            current_app.logger.debug("🔍 LIMIT count查询没有租户ID，返回0")
        return 0

    # 检查是否已经有租户过滤条件
    if self._has_tenant_filter():
        if current_app and current_app.debug:
            current_app.logger.debug("🔍 LIMIT count查询已有租户过滤，直接执行")
        return Query.count(self)

    # 执行查询并手动过滤后计数
    if current_app and current_app.debug:
        current_app.logger.debug("🔍 LIMIT count查询执行后手动过滤计数")

    try:
        # 执行原始查询
        results = Query.all(self)

        # 手动过滤结果并计数
        filtered_count = len([r for r in results if hasattr(r, 'tenant_id') and r.tenant_id == tenant_id])

        if current_app and current_app.debug:
            current_app.logger.debug(f"🔍 LIMIT count查询原始结果: {len(results)}, 过滤后: {filtered_count}")

        return filtered_count

    except Exception as e:
        if current_app and current_app.debug:
            current_app.logger.debug(f"🔍 LIMIT count查询处理失败: {str(e)}")
        return 0

# 将方法添加到TenantQuery类
TenantQuery._handle_limit_query = _handle_limit_query
TenantQuery._handle_limit_count = _handle_limit_count
